﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Controls;
using System.Xml.Serialization;
using HOG.Controls;
using System.ComponentModel;
using HOG;
using System.Windows;
using System.Collections.Generic;
using System.Collections;
using BaseControls;
using SimpleAnimationBehaviors;

namespace HOG
{
    public class Game
    {
        public Game(Player player)
        {
            this.script = Script.LoadScript(Script.ScriptFileName);
            this.player = player;
            this.controlConstructor = new ControlConstructor();
            this.controlConstructor.GameEvent += new GameEventHandler(OnGameEvent);
            this.controlConstructor.Created += new LevelConstructedDelegate(LevelConstructed);
            this.controlConstructor.StartCreating += new StartConstructingDelegate(LevelStartConstructing);            
        }

        #region fields const events
        private int currentLevelId;
        private LevelData currentLevelData;
        private Script script;
        private ControlConstructor controlConstructor; 
        private Player player;

        public const string IsolatedStorageSaveGame = "HOGSaveGame";
        public event LevelReadyDelegate LevelReady;
        public event StartConstructingDelegate StartLoadingLevel;
        public event GameEventHandler GameEvent;
        
        public HOG.Player Player
        {
            get { return player; }
            set { player = value; }
        }
        #endregion

        #region Options methods
        public void NewGame()
        {
            //loading game script
            loadLevel(Script.FirstLevelId);
        }

        /// <summary>
        /// Load game from file in isolated storage
        /// due to xml its really simple to hack the game :)
        /// </summary>        
        public void LoadGame()
        {
            try
            {
                IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(IsolatedStorageSaveGame, FileMode.Open, isf);
                XmlSerializer serializer = new XmlSerializer(typeof(Save));
                object o = serializer.Deserialize(isfs);

                Save s = o as Save;
                if (s != null)
                {
                    currentLevelId = s.LevelId;
                    player.Points = s.Points;
                    player.TimePlay = s.TimePlay;
                }
                else
                    throw new Exception();

                isfs.Close();
            }
            catch (Exception exc)
            {
                throw exc;
            }

            loadLevel(currentLevelId);
        }

        /// <summary>
        /// Serializes Save class into IsolatedStorage
        /// just marked; stored in db on server side in future
        /// due to xml its really simple to hack the game :)
        /// </summary>
        public void SaveGame()
        {
            Save save = new Save { LevelId = currentLevelId, Points = player.Points, TimePlay = player.TimePlay };
            try
            {
                IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
                IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(IsolatedStorageSaveGame, FileMode.Create, isf);
                XmlSerializer serializer = new XmlSerializer(typeof(Save));
                serializer.Serialize(isfs, save);
                isfs.Close();
            }
            catch (FileNotFoundException exc)
            {
                throw exc;
            }
            catch (Exception exc)
            {
                throw exc;
            }
        }

        public void Exit()
        {
            //send all to 
        }
        #endregion

        /// <summary>
        /// Starts game from provided level
        /// </summary>
        /// <param name="levelId">LevelId from which to start</param>
        private void loadLevel(int levelID)
        {
            currentLevelData = script.GetLevelData(levelID);
            controlConstructor.LoadLevel(currentLevelData.XamlFilePath);
            currentLevelId = levelID;
        }

        public bool LoadNextLevel()
        {
            if (currentLevelData.IDnextLevel != Script.GameOverId)
            {
                currentLevelId = currentLevelData.IDnextLevel;
                loadLevel(currentLevelId);
                return true;
            }
            else
                return false;
        }

        #region EventHandlers
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private void OnGameEvent(object data,GameChangeType type)
        {
            switch (type)
            {
                case GameChangeType.ItemComplete: { break; }//we just need LevelComplete event in this class
                case GameChangeType.LevelComplete: { LevelFinished(); break; }
            }
            if (GameEvent != null)
                GameEvent(data, type);
        }
        void LevelConstructed(Control levelControl)
        {
            if (LevelReady != null)
                LevelReady(levelControl, currentLevelData.Time);                         
            HOGSceneShow show = new HOGSceneShow();//start animation
            show.Attach(levelControl);
        }
        void LevelStartConstructing(WaitControl control)
        {
            if (StartLoadingLevel != null)
                StartLoadingLevel(control);
        }
        #endregion

        public void AddPoints(int goodClicks, int badClicks, int time)
        {
            int pointsForLevel = currentLevelData.PointsForLevel +
                goodClicks * currentLevelData.PointsForItem +
                badClicks * currentLevelData.PenaltyForWrongClick +
                time * currentLevelData.PointsForSecond;

            player.Points += pointsForLevel;
            player.TimePlay += time;
        }
        public IEnumerable<string> GetItems()
        {
            return controlConstructor.GetItems();
        }
        void LevelFinished()
        {
            SaveGame();
            HOGSceneHide hide = new HOGSceneHide();
            hide.Attach(controlConstructor.GetActualLevel());
        }
    }
}
